<template>
  <div class="h-[100%]">
    <vxe-grid ref="tableRef" v-bind="tableOptions">
      <template #pay_month="{ row }">
        <div>
          {{ row?.pay_due_date || "-" }}
        </div>
      </template>
      <template #operation="{ row }">
        <el-button
          type="primary"
          link
          @click="handleSubmit(row)"
          v-if="row.audit_status == 0"
          v-hasPermi="[financeManageAuthList.fund_plan.submit]"
          >提交</el-button
        >
        <el-button
          type="danger"
          link
          @click="handleDelete(row)"
          v-if="row.audit_status == 0"
          v-hasPermi="[financeManageAuthList.fund_plan.delete]"
          >删除</el-button
        >
        <el-button
          type="primary"
          link
          @click="handleEdit(row)"
          v-if="row.audit_status == 0"
          v-hasPermi="[financeManageAuthList.fund_plan.Adjust]"
          >调整</el-button
        >
        <el-button
          type="primary"
          link
          @click="handleAudit(row)"
          v-if="row.audit_status == 2"
          v-hasPermi="[financeManageAuthList.fund_plan.audit]"
          >财务确认</el-button
        >
        <el-button
          type="primary"
          link
          @click="handleLog(row)"
          v-hasPermi="[financeManageAuthList.fund_plan.log]"
          >日志</el-button
        >
      </template>
    </vxe-grid>

    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="finance.logistics-fund-plan"
      :business_id="logId"
      @close="logId = null"
    />
  </div>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { financeManageAuthList } from "@/Auth/finance-manage.js";
import {
  getNextWeekMonday,
  printFourWeeksDates,
  generateDateRangeArray,
} from "@/utils/index.js";
import { columnsData, columnsDataNext, columnsMonth } from "./data.js";
import {
  opNextWeekList,
  opNextAfter4WeekList,
  opHistoryWeekList,
  opHistory4WeekList,
  opCurrentMonthList,
  opHistoryMonthList,
  opSure,
  opSubmit,
} from "../../api/index.js";
const { proxy } = getCurrentInstance();
import Log from "@/components/Log/index.vue";
const props = defineProps({
  params: { type: Object, default: () => ({}) },
  type: { type: String, default: "NEXT_WEEK" },
  dueDate: { type: Array, default: () => [] },
});
const { params, type, dueDate } = toRefs(props);
const tableRef = ref();
const emits = defineEmits(["edit", "submit", "audit", "delete"]);
let tableColumns = JSON.parse(JSON.stringify(columnsData));
// let tableColumnsFilter = tableColumns.filter((item) => {
//   return item.field !== "operation";
// });
let tableColumnsFilter = tableColumns;
const tableOptions = reactive({
  pagerConfig: { pageSize: 20 },
  round: true,
  height: "auto",
  autoHidden: true,
  columnConfig: {
    resizable: true,
  },
  columns: tableColumnsFilter,
  proxyConfig: {
    autoLoad: true, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page }) => {
        return handleReq(page);
      },
    },
  },
});
// () => type.value
watch(
  () => type.value,
  (val) => {
    tableOptions.columns = [];
    let data = getNextWeekMonday(2);
    let time = printFourWeeksDates(data);
    const chineseNumbers = ["一", "二", "三", "四", "五", "六", "日"];
    nextTick(() => {
      console.log(val);
      switch (val) {
        case "HISTORY_WEEK":
          //将columnsData里面的操作列去掉
          let tableColumns = JSON.parse(JSON.stringify(columnsData));
          tableOptions.columns = tableColumns.filter((item) => {
            return item.field !== "operation";
          });
          break;
        case "HISTORY_4_WEEK":
          tableOptions.columns = columnsDataNext;
          // tableOptions.columns = columnsDataNext;
          break;
        case "NEXT_WEEK":
          tableOptions.columns = columnsData;
          break;
        case "NEXT_AFTER4_WEEK":
          let arr = [];
          for (let i = 0; i < 4; i++) {
            let obj = {
              title: `后${chineseNumbers[i]}周`,
              children: [],
            };
            for (let j = 0; j < 7; j++) {
              obj.children.push({
                title: `周${chineseNumbers[j]}`,
                children: [
                  {
                    field: `day_${i}_${j}`,
                    title: `${time[i][j]}`,
                    width: 110,
                  },
                ],
              });
            }
            arr.push(obj);
          }
          tableOptions.columns = [...columnsDataNext, ...arr];
          break;
        case "CURRENT_MONTH":
          tableOptions.columns = columnsMonth;
          break;
        case "HISTORY_MONTH":
          tableOptions.columns = columnsMonth;
          break;
          tableRef.value?.resetColumn();
      }
    });
  }
);
let time_history = ref([]);
watch(
  () => dueDate.value,
  (val) => {
    // tableOptions.columns = [];
    time_history.value = [];
    const chineseNumbers = ["一", "二", "三", "四", "五", "六", "日"];
    nextTick(() => {
      if (val?.length && type.value == "HISTORY_4_WEEK") {
        let time = generateDateRangeArray(val[0], val[1]);
        time_history.value = time;
        let arr = [];
        for (let i = 0; i < 4; i++) {
          let obj = {
            title: `后${chineseNumbers[i]}周`,
            children: [],
          };
          for (let j = 0; j < 7; j++) {
            obj.children.push({
              title: `周${chineseNumbers[j]}`,
              children: [
                {
                  field: `day_${i}_${j}`,
                  title: `${time[i][j]}`,
                  width: 110,
                },
              ],
            });
          }
          arr.push(obj);
        }
        tableOptions.columns = [...columnsDataNext, ...arr];
      }
      if (!val?.length && type.value == "HISTORY_4_WEEK") {
        tableOptions.columns = columnsDataNext;
      }
    });
  }
);
const handleReq = async (page) => {
  try {
    const _api = {
      HISTORY_WEEK: opHistoryWeekList,
      HISTORY_4_WEEK: opHistory4WeekList,
      NEXT_WEEK: opNextWeekList,
      NEXT_AFTER4_WEEK: opNextAfter4WeekList,
      CURRENT_MONTH: opCurrentMonthList,
      HISTORY_MONTH: opHistoryMonthList,
    };
    const res = await _api[type.value]({
      ...params.value,
      ...page,
    });
    const { total } = res;
    // const data = res?.data || {};
    const data = updataTable(res?.data);
    return { data, total };
  } catch (e) {
    console.error(e);
  }
};

const updataTable = (data) => {
  switch (type.value) {
    case "HISTORY_4_WEEK":
      data?.forEach((item) => {
        let ind = findNumberInArray(
          item?.expected_pay_date,
          time_history.value
        );
        if (ind) {
          item[`day_${ind[0]}_${ind[1]}`] = item?.amount;
        }
      });
      break;
    case "NEXT_AFTER4_WEEK":
      let day = getNextWeekMonday(2);
      let time = printFourWeeksDates(day);
      data?.forEach((item) => {
        let ind = findNumberInArray(item?.expected_pay_date, time);
        if (ind) {
          item[`day_${ind[0]}_${ind[1]}`] = item?.amount;
        }
      });
      break;
  }
  return data;
};
function findNumberInArray(target, arr) {
  for (let i = 0; i < arr?.length; i++) {
    for (let j = 0; j < arr[i]?.length; j++) {
      if (arr[i][j] === target) {
        return [i, j];
      }
    }
  }
  return null;
}
//日志
const logVisible = ref(false);
const logId = ref(null);
const handleLog = (item) => {
  logId.value = item?.id;
  logVisible.value = true;
};
const handleAudit = (item) => {
  emits("audit", item.id);
};
//提交
const handleSubmit = (item) => {
  emits("submit", item.id);
};

const handleEdit = (row) => {
  emits("edit", row);
};

//删除
const handleDelete = (item) => {
  emits("delete", item.id);
};
defineExpose({ tableRef });
</script>

<style lang="scss" scoped></style>
